#!/usr/bin/python

# Copyright (c) 2010-, WangFei, Cloud Team, CGCL,
# All rights reserved.
# This program send data to a VM. Using as follow:
#              python senddata -machinefile ip "local_data_path"
# for example: python senddata -machinefile ip "/root/a.txt"
#               

import os, sys
import paramiko

def send_date_to_master(remote_address,username,password,ssh_port,local_data_path,remote_data_path):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect((remote_address), username=(username), password=(password), port=(ssh_port))
    sftpclient = client.open_sftp()	
    sftpclient.put(local_data_path,remote_data_path,callback=None)
    sftpclient.close()
    client.close()

def GetIpAndPassword(machinefile):
    global remote_address
    global password
    path=sys.path[0]
    fp_intr = open(path+'/'+machinefile,'r')
    line = fp_intr.readline()
    length=len(line)
    line=line[0:length-1]
    remote_address,password=line.split(' ')
    fp_intr.close()

remote_address=0
password=""

if __name__ == "__main__":
    cnt_argv = len(sys.argv)
    if cnt_argv != 4:
        print "Command format error. Please Using As follow:"
        print "      python senddata -machinefile ip_password_list_file data_path"
        sys.exit(0)
    username="root"
    ssh_port=22
    flag = os.path.exists(sys.argv[2])
    if not flag:
        print sys.argv[2] + " is not exist."
        sys.exit(0)
    GetIpAndPassword(sys.argv[2])

    local_data_path = sys.argv[3]

    flag = os.path.exists(local_data_path)
    if not flag:
        print local_data_path + " is not exist."
        sys.exit(0)

    remote_data_path="/home/cgcl/"
    tmp = local_data_path.split("/")
    remote_data_path+=tmp[-1]
    print "Send " + local_data_path +" to " + remote_address+"@"+remote_data_path
    send_date_to_master(remote_address,username,password,ssh_port,local_data_path,remote_data_path)
